package com.fh.fruit.service.baseareagoods.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.fh.dao.DaoSupport;
import com.fh.entity.Page;
import com.fh.fruit.entity.areagooddetail.AreaGoodDetail;
import com.fh.fruit.entity.areagooduser.AreaGoodUser;
import com.fh.fruit.entity.baseareagoods.AreaGoodsCount;
import com.fh.fruit.entity.baseareagoods.GoodsSpec;
import com.fh.fruit.service.baseareagoods.AreaGoodsCountManager;
import com.fh.util.DateUtil;
import com.fh.util.PageData;

import cn.jiguang.common.utils.StringUtils;

/**
 * 区域商品Service
 * 
 * @author Administrator
 * @version 2017.11.30 15:39
 */
@Service("areaGoodsCountService")
public class AreaGoodsCountService implements AreaGoodsCountManager {
	@Resource(name = "daoSupport")
	private DaoSupport dao;

	@Override
	@SuppressWarnings("unchecked")
	public List<AreaGoodsCount> listAreaGoods(Page page) throws Exception {
		return (List<AreaGoodsCount>) dao.findForList("AreaGoodsCountMapper.areaGoodslistPage", page);
	}

	@Override
	public int saveAreaGoods(PageData pd) throws Exception {
		return (int) dao.save("AreaGoodsCountMapper.saveAreaGoodsCount", pd);
	}

	@Override
	public int deleteAreaGoods(PageData pd) throws Exception {
		return (int) dao.delete("AreaGoodsCountMapper.delAreaGoods", pd);
	}
	@Override
	public int selectTotalsByCode(PageData pd) throws Exception {
		return (int) dao.findForObject("AreaGoodsCountMapper.selectTotals", pd);
	}
	@Override
	public int updateState(PageData pd) throws Exception {
		String state = pd.getString("state");
		//下架
		if ("00".equals(state)) {
			PageData parms = new PageData();
			parms.put("state",  "01");
			parms.put("areaGoodsCountId", pd.getString("id"));
			//判断时间表是否存在已上架期次
			int gst = (int) dao.findForObject("GoodsSpecTimeMapper.selectTotals", parms);
			if (gst > 0) {
				//商品时间上架中，不能下架
				return 2;
			} else {
				return (int) dao.update("AreaGoodsCountMapper.updateState", pd);
			}
		} else { //上架
			return (int) dao.update("AreaGoodsCountMapper.updateState", pd);
		}
	}

	@Override
	public AreaGoodsCount findById(PageData pd) throws Exception {
		return (AreaGoodsCount) dao.findForObject("AreaGoodsCountMapper.findById", pd);
	}

	@Override
	public int selectTotalAreaGoods(PageData pd) throws Exception {
		return (int) dao.findForObject("AreaGoodsCountMapper.selectTotalAreaGoods", pd);
	}
	@Override
	public AreaGoodsCount selectByConditions(AreaGoodsCount ag) throws Exception {
		return (AreaGoodsCount) dao.findForObject("AreaGoodsCountMapper.selectByConditions", ag);
	}

	@Override
	public String insertAreaGoods(PageData pd) throws Exception {
		StringBuffer str = new StringBuffer();
		// 基地ID
		String baseId = pd.getString("baseId");
		// 基地区域ID
		String baseAreaId = pd.getString("baseAreaId");
		// 商品规则ID
		String goodsSpecId = pd.getString("goodsSpecId");
		// 获取创建时间
		String createTime = DateUtil.getTime();
		//批次号码
		String batchNumber = pd.getString("batchNumber");
		//是否合并
		String flag = pd.getString("flag");
		
		if (StringUtils.isEmpty(baseId)) {
			str.append("无法获取基地ID，操作失败");
		}
		if (StringUtils.isEmpty(baseAreaId)) {
			str.append("无法获取基地区域ID，操作失败");
		}
		if (StringUtils.isEmpty(goodsSpecId)) {
			str.append("无法获取商品规则ID，操作失败");
		}
		if (!"1".equals(flag)) { //不合并时校验
			if (StringUtils.isEmpty(batchNumber)) {
				str.append("无法获取批次号，操作失败");
			}
		}
		
		// 获取商品数量
		String goodNum = pd.getString("num");
		int num = 0;
		if (StringUtils.isNotEmpty(goodNum)) {
			num = Integer.valueOf(goodNum);
			if (num <= 0) {
				str.append("新增商品数量不能小于0！");
			}
		}

		if (str.length() > 0) {
			return str.toString();
		}
		
		// 根据基地ID,区域Id,商品规则ID，种植日期判断是否存，存在更新，不存在新增
		AreaGoodsCount prams  = new AreaGoodsCount();
		prams.setBaseId(Integer.valueOf(baseId));
		prams.setBaseAreaId(Integer.valueOf(baseAreaId));
		prams.setGoodsSpecId(Integer.valueOf(goodsSpecId));
		prams.setBirthday(pd.getString("birthday"));
		AreaGoodsCount areaG = (AreaGoodsCount) dao.findForObject("AreaGoodsCountMapper.selectByConditions", prams);
		if (areaG != null && areaG.getId() > 0) { //update
			PageData psData = new PageData();
			psData.put("version", areaG.getVersion());
			psData.put("id", areaG.getId());
			psData.put("num", areaG.getNum() + num);
			int record = (int) dao.update("AreaGoodsCountMapper.updateAreaGoods", psData);
			if (record <= 0) {
				return "操作失败！";
			}
			pd.put("id", areaG.getId());
		} else { //insert
			// 区域商品统计ID
			pd.put("state", "00");
			pd.put("takeNum", 0);
			dao.save("AreaGoodsCountMapper.saveAreaGoodsCount", pd);
		}
		
		String areaGoodsCountId = String.valueOf(pd.get("id"));
		// 构建区域商品用户关系
		List<AreaGoodDetail> agDetail = new ArrayList<AreaGoodDetail>();
		
		PageData ps = new PageData();
		if ("1".equals(flag)) { //合并时取count表批次号
			ps.put("batchNumber", areaG.getBatchNumber());
		} else {
			ps.put("batchNumber", batchNumber);
		}
		ps.put("areaGoodsCountId", areaGoodsCountId);
		Integer seq = (Integer) dao.findForObject("AreaGoodDetailMapper.selectSeq", ps);
		if (seq == null) {
			seq = 0;
		}
		// 根据商品数量初始化商品详情
		for (int i = 0; i < num; i++) {
			// 区域商品详情
			AreaGoodDetail ag = new AreaGoodDetail();
			ag.setAreaGoodsCountId(Integer.valueOf(areaGoodsCountId));
			int codeNum = seq + i + 1;
			if ("1".equals(flag)) { //合并时取count表批次号
				ag.setBatchNumber(areaG.getBatchNumber());
			} else {
				ag.setBatchNumber(batchNumber);
			}
			
			ag.setSeq(codeNum);
			ag.setCreateTime(createTime);
			ag.setOperatorId(pd.getString("operatorId"));
			agDetail.add(ag);
			
		}
		int batchCount = 1000; //每批执行个数
		int batchLastIndex = batchCount; //每一批最后一条记录的下标
		for (int index = 0; index < agDetail.size();) {
			if (batchLastIndex >= agDetail.size()) {
				batchLastIndex = agDetail.size(); //设置下一批启示坐标
				//构建本批次处理数据
				List<AreaGoodDetail> batchList = agDetail.subList(index, batchLastIndex);
				//保存商品详情
				dao.save("AreaGoodDetailMapper.insertGoodDetilsbatch", batchList);
				// 构建区域商品用户关系
				List<AreaGoodUser> areaGoodUser = new ArrayList<AreaGoodUser>();
				for (AreaGoodDetail agd : batchList) {
					AreaGoodUser au = new AreaGoodUser();
					// 时间产品id
					au.setAreaGoodsId(agd.getId());
					// 未绑定
					au.setIsBinding("00");
					areaGoodUser.add(au);
				}
				// 商品用户绑定
				dao.save("AreaGoodUserMapper.insertGoodUserBatch", areaGoodUser);
				break; //执行完毕，退出循环
			} else {
				//构建本批次处理数据
				List<AreaGoodDetail> bcList = agDetail.subList(index, batchLastIndex);
				//保存商品详情
				dao.save("AreaGoodDetailMapper.insertGoodDetilsbatch", bcList);
				// 构建区域商品用户关系
				List<AreaGoodUser> areaGoodUser = new ArrayList<AreaGoodUser>();
				for (AreaGoodDetail agd : bcList) {
					AreaGoodUser au = new AreaGoodUser();
					// 时间产品id
					au.setAreaGoodsId(agd.getId());
					// 未绑定
					au.setIsBinding("00");
					areaGoodUser.add(au);
				}
				// 商品用户绑定
				dao.save("AreaGoodUserMapper.insertGoodUserBatch", areaGoodUser);
				
				index = batchLastIndex; // 设置下一批下标
                batchLastIndex = index + batchCount;
			}
		}
		
		return str.toString();
	}
	@Override
	@SuppressWarnings("unchecked")
	public List<AreaGoodUser> listAreaGoodDetails(Page page) throws Exception {
		return (List<AreaGoodUser>) dao.findForList("AreaGoodUserMapper.goodDetialslistPage", page);
	}

	@Override
	public String deleteGoodDetails(PageData pd) throws Exception {
		//根据id 获取商品，判断商品的状态，上架则不能执行删除，下架状态判断 总量和订购数量的差值是否大于要删除数据量，小于则直接返回
		String delNum = pd.getString("delNum"); // 删除商品详情的数量
		String id = pd.getString("id"); // 区域商品id
		StringBuffer str = new StringBuffer();
		if (StringUtils.isEmpty(delNum)) {
			str.append("删除数量必须为大于0的数字");
		}
		if (StringUtils.isEmpty(id)) {
			str.append("区域商品id不能为空");
		}
		if (str.length() > 0) {
			return str.toString();
		}
		PageData prams = new PageData();
		prams.put("id", id.trim());
		AreaGoodsCount agc = (AreaGoodsCount) dao.findForObject("AreaGoodsCountMapper.findById", prams);
		if (agc != null) {
			String agState = agc.getState();
			int num = agc.getNum();
			int takeNum = 0;
			if (agc.getTakeNum() != null) {
				takeNum = agc.getTakeNum();
			}
			int version = agc.getVersion();
			int dNum = Integer.valueOf(delNum); //要删除的数量
			if ("00".equals(agState)) {
				if ((num - takeNum) >= dNum) {
					//1、更新总量 减小
					PageData psData = new PageData();
					psData.put("version", version);
					psData.put("id", id);
					psData.put("num", num - dNum);
					int record = (int) dao.update("AreaGoodsCountMapper.updateAreaGoods", psData);
					if (record == 1) {
						//2、查询排序后删除数量的商品详情id
						PageData agdu = new PageData();
						agdu.put("id", id);
						agdu.put("countState", "00"); //未上架
						agdu.put("isBinding", "00"); //未绑定
						agdu.put("limtNum", dNum);
						@SuppressWarnings("unchecked")
						List<AreaGoodDetail> lagd = (List<AreaGoodDetail>) dao.findForList("AreaGoodDetailMapper.selectGoodDetails", agdu);
						if (lagd == null || lagd.size() < dNum) {
							throw new Exception("可删除数量小于要删除数量，操作失败");
						}
						StringBuffer ids = new StringBuffer();
						for (AreaGoodDetail a : lagd) {
							if (ids.length() > 0) {
								ids.append(",").append(a.getId());
							} else {
								ids.append(a.getId());
							}
						}
						
						//3、删除商品用户绑定
						PageData agu = new PageData();
						agu.put("ids", ids.toString());
						agu.put("isBinding", "00"); //未绑定
						int aguNum = (int) dao.delete("AreaGoodUserMapper.deleteGoodUser", agu);
						if (aguNum != dNum) {
							throw new Exception("删除区域商品用户数据失败");
						}
						//4、删除区域详情信息
						PageData agd = new PageData();
						agd.put("ids", ids.toString());
						int agdNum = (int) dao.delete("AreaGoodDetailMapper.deleteGoodDetails", agd);
						if (agdNum != dNum) {
							throw new Exception("删除区域商品详情数据失败");
						}
					} else { 
						throw new Exception("更新区域商品统计数据失败");
					}
					
				} else {
					str.append("删除区域商品详情数量大于可删除数量，操作失败！");
				}
			} else {
				str.append("区域商品为已上架状态，不能删除区域商品详情数据！");
			}
		} else {
			str.append("未发现未上架状态的该区域商品");
		}
		return str.toString();
	}
	
	@Override
	@SuppressWarnings("unchecked")
	public List<GoodsSpec> listGoodsSpec(Page page) throws Exception {
		return (List<GoodsSpec>) dao.findForList("GoodsSpecMapper.goodsSpeclistPage", page);
	}
	
}
